package com.guavestudios.fnfo.utils {
	import com.guavestudios.fnfo.Fnfo;
	import com.guavestudios.utils.Format;
	import flash.events.Event;
	import flash.utils.Dictionary;
	import flash.utils.getTimer;
	/**
	 * Error handler for error catching in functions
	 * its a workaround for player < 10.1
	 * @author maze
	 */
	public class FnfoErrorHandler{
		
		protected static var handels:Dictionary = new Dictionary(true);
		protected static var _active:Boolean=false;
		
		protected static var DEFAULT_FNC:Function = function():void { };
		public static function addHandle(fnc:Function):Function {
			if (!_active) return fnc;
			//var lh:String = "hallo string";
			var cfnc:Function = function(e:Event):void {
				//trace("(FnfoErrorHandler.addHandle) lh: " + e.type);
				try {
					fnc(e);
				} catch (ex:Error) {
					handleError(ex);
					throw ex;
				}
			}
			handels[fnc] = cfnc;
			return cfnc;
		}
		public static function removeHandle(fnc:Function):Function {
			if (!_active) return fnc;
			var nc:Function = handels[fnc];
			if (nc == null) return DEFAULT_FNC;
			return nc;
		}
		public static function handleError(ex:Error):void {
			var st:String = ex.getStackTrace();
			st = st.substring(0, st.lastIndexOf("\n"));
			var d:Date = new Date(getTimer());
			st += Format.format("\n\t Time: {4} Execution: {0:d##}:{1:d##}:{2:d##}:{3:d###}",
				d.hoursUTC,d.minutesUTC,d.secondsUTC,d.millisecondsUTC,(new Date()).toUTCString());
			trace(st);
			
			Fnfo.getInstance().data["lastError"] = st;
		}
		public function FnfoErrorHandler() {
			
		}
		
		static public function get active():Boolean { return _active; }
		
		static public function set active(value:Boolean):void {
			_active = value;
		}
		
	}

}